<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>table模块快速使用</title>
    <link rel="stylesheet" href="/plugins/layui/css/layui.css" media="all">
    <link rel="stylesheet" type="text/css" href="/build/css/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/css/my-style.css">
    <link th:href="@{/ajax/libs/jquery-ztree/3.5/css/metro/zTreeStyle.css}" rel="stylesheet"/>

</head>
<style>
    .layui-form-label {
        width: 86px;
        padding: 9px 9px;
    }

</style>

<body>
<div class="kit-doc">

    <!--表格搜索框组-->
    <div class="layui-form-item layui-formgroup layui-tab-card">
        <!-- input输入框 -->
        <div class="layui-inline">
            <label class="layui-form-label">项目名称：</label>
            <div class="layui-input-inline">
                <input name="phone" autocomplete="off"
                       class="layui-input" type="tel" id="projectName">
            </div>
        </div>

        <!-- input输入框 -->
        <div class="layui-inline">
            <label class="layui-form-label">项目编号：</label>
            <div class="layui-input-inline">
                <input name="phone" autocomplete="off"
                       class="layui-input" id="projectId">
            </div>
        </div>

        <!-- 按钮 -->
        <button class="layui-btn" id="searchBtn">搜索</button>
    </div>

    <div class="layui-card layui-card-body">
        <!-- 表格增删改查btn -->
        <div class="layui-btn-group layui-m-b-5">
            <button class="layui-btn layui-btn-sm" id="modal1"><i class="fa fa-plus"></i>&nbsp;增加
            </button>
        </div>
        <table class="layui-table xuhao-table" id="table-context" lay-filter="test">
            <script type="text/html" id="barDemo">
                <a class="layui-btn layui-btn-xs" lay-event="member-management">成员管理</a>
                <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
            </script>
        </table>
    </div>


</div>

<!--选择项目经理弹出 table-->
<div id="hidden1" lay-filter="hidden1" style="display: none">
    <table id="user_result" lay-filter="projectManager_result"></table>
</div>

<!-- 添加 弹出用户表格的 tool（里面的按钮）-->
<script type="text/html" id="hidden1-table-tool">
    <a class="layui-btn layui-btn-xs" lay-event="select">选择</a>
</script>

<!-- 弹框content -->
<div id="modal-content1" style="display: none; padding:20px;">
    <form class="layui-form" action="" id="addForm">
        <div class="layui-form-item">
            <label class="layui-form-label">项目编号
                <span style="color: #ff393c;">★</span>：
            </label>

            <div class="layui-input-block">
                <input type="text" name="projectId" required lay-verify="required"
                       placeholder="请输入项目编号"
                       autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">项目名
                <span style="color: #ff393c;">★</span>：
            </label>
            <div class="layui-input-block">
                <input type="text" name="projectName" required lay-verify="required"
                       placeholder="请输入项目名"
                       autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">项目经理
                <span style="color: #ff393c;">★</span>：
            </label>
            <div class="layui-input-block">
                <input id="projectManager" type="text" name="managerName" required lay-verify="required"
                       placeholder="请选择项目经理"
                       autocomplete="off" class="layui-input">
                <input id="manager" type="text" name="manager" required lay-verify="required"
                       autocomplete="off" class="layui-input" style="display: none">
            </div>
        </div>

        <div class="layui-form-item">
            <input name="deptId" type="hidden" id="treeId"/>
            <label class="layui-form-label">选择部门
                <span style="color: #ff393c;">★</span>：
            </label>
            <div class="layui-input-block" style="height: 200px;overflow-y: scroll">
                <div id="tree" class="ztree"></div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">开始时间
                <span style="color: #ff393c;">★</span>：
            </label>
            <div class="layui-input-block">
                <input type="text" class="layui-input" id="startDate" name="startDate"
                       placeholder="yyyy-MM-dd" lay-verify="required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">结束时间
                <span style="color: #ff393c;">★</span>：
            </label>
            <div class="layui-input-block">
                <input type="text" class="layui-input" id="endDate" th:name="endDate"
                       placeholder="yyyy-MM-dd" lay-verify="required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">总工时(小时)
                <span style="color: #ff393c;">★</span>：
            </label>
            <div class="layui-input-block">
                <input type="text" class="layui-input" id="worktimeTotal" th:name="worktimeTotal"
                       lay-verify="required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">启用/禁用：</label>
            <div class="layui-input-block">
                <input type="checkbox" name="status" id="status" lay-skin="switch" lay-text="启用|禁用"
                       lay-filter="switchStatus">
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">备注：</label>
            <div class="layui-input-block">
                <textarea name="remark" placeholder="请输入内容" id="remark"
                          class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block" style="margin-left: 50%;margin-top: 8%">
                <button class="layui-btn" lay-submit="" lay-filter="formDemo">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>

<!-- 成员管理弹框content-->
<div id="member-management-content" style="display: none; padding:20px">

    <div class="layui-row">
        <div class="layui-col-md6">
            <div class="layui-card layui-card-body gs-box">
                <div>成员列表</div>
                <div id="tb1" style="height:auto"></div>
                <table class="layui-table xuhao-table " id="table-management1" lay-filter="test1">
                    <script type="text/html" id="barDemo1">
                        <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="remove">移除</a>
                    </script>
                </table>
            </div>
        </div>
        <div class="layui-col-md6">
            <div class="layui-card-body gs-box">
                <div id="tb2" style="height:auto"></div>
                <div>候选成员</div>
                <table class="layui-table xuhao-table " id="table-management2" lay-filter="test2">
                    <script type="text/html" id="barDemo2">
                        <a class="layui-btn layui-btn-normal layui-btn-sm" lay-event="join">添加</a>
                    </script>
                </table>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="toolbarDemo1">
    <div class="layui-btn-container">
        <button class="layui-btn" lay-event="batchDel">批量移除</button>
    </div>
</script>
<script type="text/html" id="toolbarDemo2">
    <div class="layui-btn-container">
        <button class="layui-btn" lay-event="batchAdd">批量添加</button>
    </div>
</script>

<!--部门id转名字模板-->
<script type="text/html" id="deptTpl">
    {{ fn(d.deptId) }}
</script>

<!--状态模板-->
<script type="text/html" id="statusTpl">
    <input type="checkbox" name="sex" value="{{d.status}}" lay-skin="switch" lay-text="启用|禁用"
           readonly="readonly" disabled="disabled"
           lay-filter="status" {{ d.status== '0' ? 'checked' : '' }}>
</script>
<script type="text/javascript" src="../../static/js/jquery.min.js"
        th:src="@{/js/jquery.min.js}"></script>
<script th:src="@{/ajax/libs/jquery-ztree/3.5/js/jquery.ztree.all-3.5.js}"></script>
<script src="/plugins/layui/layui.js"></script>
<script th:inline="javascript">
    // 获取角色list
    var deptList = [[${deptList}]];
    // id 部门map
    var idDeptMap = new Map();
    for (var i = 0; i < deptList.length; i++) {
        idDeptMap.set(deptList[i].id, deptList[i].deptName);
    }
</script>
<script>
    // 部门id转名字
    var fn = function (deptIds) {
        var idList = deptIds.split(",")
        var str = "";
        for (var i = 0; i < idList.length; i++) {
            str += idDeptMap.get(idList[i]) + ",";
        }
        return str.substr(0, str.length - 1);
    };
</script>
<script src="/js/ry-ui.js"></script>
<script>
    /*用户管理-新增-选择部门树*/
    function selectDeptTree() {
        var treeId = $("#treeId").val();
        var deptId = treeId == null || treeId == "" ? "100" : treeId;
        var url = "/system/dept/selectDeptTree/" + deptId;
        layer.open({
            title: "选择部门",
            type: 2,
            content: url,
            area: ['22%', '45%'],
            shadeClose: true
        });
    }
</script>

<script>
    layui.use(['table', 'jquery'], function () {
        var table = layui.table;
        var $ = layui.$;
        var projectTable = table.render({
            elem: '#table-context'
            , url: '/project/list'
            , height: 'full-200'
            , page: true
            , limit: 10
            , limits: [10, 20, 30]
            , even: true
            , request: {
                pageName: 'page' //页码的参数名称，默认：page
                , limitName: 'size' //每页数据量的参数名，默认：limit
            }
            , cols: [
                [
                    {field: 'projectId', title: '项目编号', width: '12%', align: 'center'},
                    {field: 'projectName', title: '项目名', width: '15%', align: 'center'},
                    {
                        field: 'deptName',
                        title: '部门名', width: '10%',
                        align: 'center',
                        templet: '#deptTpl'
                    },
                    {
                        field: 'managerName',
                        title: '项目经理', width: '10%',
                        align: 'center'
                    }
                    , {field: 'worktimeTotal', width: '9%', title: '总工时(小时)', align: 'center'}
                    , {
                    field: 'startDate',
                    width: '9%',
                    title: '开始时间',
                    align: 'center',
                    sort: true,
                    templet: "<div>{{layui.util.toDateString(d.startDate, 'yyyy-MM-dd')}}</div>"
                }
                    , {
                    field: 'endDate',
                    width: '9%',
                    title: '结束时间',
                    align: 'center',
                    sort: true,
                    templet: "<div>{{layui.util.toDateString(d.endDate, 'yyyy-MM-dd')}}</div>"
                },
                    {
                        field: 'status', width: '8%', title: '状态', align: 'center', templet: '#statusTpl'
                    }
                    , {
                    fixed: 'right',
                    minWidth: 200,
                    title: "操作",
                    align: 'center',
                    toolbar: '#barDemo',
                    format: function () {

                    }
                }
                ]
            ],
            done: function (res, curr, count) {
            }
        });
        //监听行工具事件
        table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'del') {
                layer.confirm('确定删除当前项目？', function (index) {
                    console.log("当前行的数据为：" + data.id);
                    obj.del(); //删除对应行（tr）的DOM结构
                    layer.close(index);
                    //向服务端发送删除指令
                    layui.$.ajax({
                        type: 'DELETE',
                        url: "/project/del/" + data.id,
                        success: function (res) {
                            layer.closeAll();
                            if (res.code == 0) {
                                layer.msg("删除成功");
                            } else {
                                layer.msg("删除失败" + data.msg);
                            }
                        }
                    });
                });
            } else if (layEvent === 'edit') {
                // 编辑操作
                layui.layer.open({
                    title: "内容修改",
                    type: 2,
                    content: ["/project/update/" + data.id, 'yes'],
                    area: ['40%', '88%'],
                    shadeClose: true
                });
            } else if (layEvent === 'member-management') {
                // 获取选中项目的id
                var projectId = data.id
                // 获取选中项目经理的id
                var manager = data.manager
                var userTable;// 已在项目成员表格
                var userOutTable;// 候选项目成员表格
                // 成员管理
                layui.layer.open({
                    title: "成员管理",
                    type: 1,
                    content: $("#member-management-content"),
                    area: ['70%', '85%'],
                    shadeClose: true,
                    end: function () {
                        // 弹出层关闭后的动作
                    }
                });


                // 已在项目成员
                layui.use(['table', 'jquery', 'form'], function () {
                    var table = layui.table;
                    var $ = layui.$;
                    var form = layui.form;
                    userTable = table.render({
                        elem: '#table-management1'
                        , url: '/project/userList'
                        , toolbar: '#toolbarDemo1'
                        , height: '470'
                        , page: true
                        , limit: 10
                        , limits: [10, 20, 30]
                        , request: {
                            pageName: 'page' //页码的参数名称，默认：page
                            , limitName: 'size' //每页数据量的参数名，默认：limit
                        }, where: { //设定异步数据接口的额外参数，任意设
                            projectId: projectId
                        }
                        , cols: [
                            [
                                {type: 'checkbox', fixed: 'left'},
                                {
                                    field: 'userName',
                                    title: '用户名',
                                    align: 'center'
                                },
                                {
                                    field: 'joinTime',
                                    align: 'center',
                                    title: '加入日期',
                                    templet : "<div>{{layui.util.toDateString(d.joinTime, 'yyyy-MM-dd')}}</div>"
                                },
                                {
                                    title: '操作',
                                    fixed: 'right',
                                    align: 'center',
                                    toolbar: '#barDemo1'
                                }
                            ]
                        ]
                        , done: function (res, curr, count) {
                        }
                    });

                    //成员列表 头工具栏事件 批量移除成员
                    table.on('toolbar(test1)', function (obj) {
                            var checkStatus = table.checkStatus('table-management1');
                            switch (obj.event) {
                                case 'batchDel':
                                    idList = [];//存储选中的成员id user_id
                                    var data = checkStatus.data;
                                    for (var i = 0; i < data.length; i++) {
                                        idList.push(data[i].userId);
                                    }
                                    //没有选中任何一行
                                    if (idList.length == 0) {
                                        layui.layer.msg('请选择用户');
                                        return;
                                    }
                                    layui.layer.confirm('确定移除选中用户吗？', function (index) {
                                        layui.layer.close(index);
                                        layer.msg('移除中...', {icon: 16, shade: 0.3, time: 5000});
                                        let postData = {
                                            "idList": idList,
                                            "projectId": projectId
                                        }
                                        layui.$.ajax({
                                            type: 'post',
                                            url: "/project/batch/remMember",
                                            traditional: true,
                                            dataType: 'json',
                                            data: postData,
                                            success: function (res) {
                                                // layer.closeAll();
                                                // 刷新两边表格
                                                refresh(projectId,manager)
                                                if (res.code == 0) {
                                                    layer.msg("删除成功");
                                                } else {
                                                    layer.msg("删除失败" + data.msg);
                                                }
                                            }
                                        });
                                    });
                                    break;
                            }

                        }
                    );
                    //成员列表 监听行删除工具事件
                    table.on('tool(test1)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                        var data = obj.data //获得当前行数据
                            , layEvent = obj.event; //获得 lay-event 对应的值
                        if (layEvent === 'remove') {
                            layer.confirm('真的移除该成员么', function (index) {
                                layer.close(index);
                                // 向服务端发送删除指令
                                layui.$.ajax({
                                    type: 'POST',
                                    url: "/project/remMember",
                                    data: {
                                        userId: data.userId,
                                        projectId: projectId
                                    },
                                    dataType: "json",
                                    success: function (res) {
                                        //关闭所有弹出层
                                        // layer.closeAll();
                                        // 刷新两边表格
                                        refresh(projectId,manager)
                                        if (res.code == 0) {
                                            layer.msg("删除成功");
                                        } else {
                                            layer.msg("删除失败" + res.msg);
                                        }
                                    }
                                });
                            });
                        }
                    });
                });
                // 候选项目成员
                layui.use(['table', 'jquery', 'form'], function () {
                    var table = layui.table;
                    var $ = layui.$;
                    var form = layui.form;
                    userOutTable = table.render({
                        elem: '#table-management2'
                        , url: '/project/userOutList'
                        , toolbar: '#toolbarDemo2'
                        , height: '470'
                        , page: true
                        , limit: 10
                        , limits: [10, 20, 30]
                        , request: {
                            pageName: 'page' //页码的参数名称，默认：page
                            , limitName: 'size' //每页数据量的参数名，默认：limit
                        },
                        where: {
                            projectId: projectId,
                            manager: manager
                        }
                        , cols: [
                            [
                                {type: 'checkbox', fixed: 'left'},
                                {
                                    field: 'userName',
                                    title: '用户名',
                                    align: 'center'
                                },
                                {
                                    title: '操作',
                                    fixed: 'right',
                                    align: 'center',
                                    toolbar: '#barDemo2'
                                }
                            ]
                        ]
                        , done: function (res, curr, count) {
                        }
                    });

                    //候选项目成员 头工具栏事件 批量添加成员
                    table.on('toolbar(test2)', function (obj) {
                            var checkStatus = table.checkStatus(obj.config.id);
                            //存储选中的成员信息
                            mumberList = [];
                            switch (obj.event) {
                                case 'batchAdd':
                                    var data = checkStatus.data;
                                    for (var i = 0; i < data.length; i++) {
                                        // 定义成员对象
                                        var mumber = {
                                            userId: '',
                                            proId: '',
                                            userName: '',
                                            joinTime: ''
                                        }
                                        mumber.proId = projectId;
                                        mumber.userName = data[i].userName;
                                        mumber.userId = data[i].id;
                                        mumberList.push(mumber)
                                    }
                                    //没有选中任何一行
                                    if (mumberList.length == 0) {
                                        layui.layer.msg('请选择用户');
                                        return;
                                    }
                                    layui.layer.confirm('确定添加选中用户到项目吗？', function (index) {
                                        layui.layer.close(index);
                                        layer.msg('添加中...', {icon: 16, shade: 0.3, time: 5000});
                                        layui.$.ajax({
                                            type: 'post',
                                            url: "/project/batch/addMember",
                                            traditional: true,
                                            contentType: 'application/json',
                                            dataType: 'json',
                                            data: JSON.stringify(mumberList),
                                            success: function (res) {
                                                // layer.closeAll();
                                                // 刷新两边表格
                                                refresh(projectId,manager)
                                                if (res.code == 0) {
                                                    layer.msg("添加成功");
                                                } else {
                                                    layer.msg("添加失败" + data.msg);
                                                }
                                            }
                                        });

                                    });
                                    break;
                            }
                        }
                    );
                    //候选项目成员 监听行工具事件
                    table.on('tool(test2)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                        var data = obj.data //获得当前行数据
                            , layEvent = obj.event; //获得 lay-event 对应的值
                        // 添加项目成员
                        if (layEvent === 'join') {
                            layui.$.ajax({
                                type: 'POST',
                                url: "/project/addMember",
                                data: {
                                    userId: data.id,
                                    projectId: projectId,
                                    userName: data.userName
                                },
                                dataType: "json",
                                success: function (res) {
                                    // layer.closeAll();
                                    // 刷新两边表格
                                    refresh(projectId,manager)
                                    if (res.code == 0) {
                                        layer.msg("添加成功");
                                    } else {
                                        layer.msg("添加失败" + res.msg);
                                    }
                                }
                            });
                        }
                    });

                });

                function refresh(projectId,manager){
                    console.log('调用了刷新')
                    userTable.reload({
                        where: { //设定异步数据接口的额外参数，任意设
                            projectId: projectId
                        }
                    });

                    userOutTable.reload({
                        where: { //设定异步数据接口的额外参数，任意设
                            projectId: projectId,
                            manager: manager
                        }
                    });
                }
            }
        });

        // 查询
        $("#searchBtn").click(function () {
            projectTable.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    projectName: $("#projectName").val(),
                    projectId: $("#projectId").val()
                }
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        })
    });



</script>

<!--弹框-->
<script>
    var $ = layui.jquery,
        layer = layui.layer;

    $('#modal1').on('click', function () {
        layer.open({
            title: "内容添加",
            type: 1,
            content: $("#modal-content1"),
            area: ['40%', '88%'],
            shadeClose: true,
            end: function () {
                //关闭窗口时清空表单内容
                $("#addForm").find('input[type=text],select,textarea,input[type=hidden]').each(function () {
                    $(this).val('');
                });

                //以下代码实现重置树
                var treeObj = $.fn.zTree.getZTreeObj("tree");
                treeObj.checkAllNodes(false);
            }
        });
    });
</script>

<script>

    // 增加项目表单
    layui.use(['form', 'layedit', 'laydate', 'jquery', 'table'], function () {
        var form = layui.form
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate;

        //常规用法
        laydate.render({
            elem: '#startDate'
        });
        laydate.render({
            elem: '#endDate'
        });


        //页面上隐藏的用于弹层的所有客户的列表的相关设置
        var user_result_table_options = {
            elem: '#user_result'
            , url: '/project/users'
            , method: 'get'
            , title: '用户列表'
            , page: true
            , limit: 10
            , limits: [10, 20, 30]
            , request: {
                pageName: 'page' //页码的参数名称，默认：page
                , limitName: 'size' //每页数据量的参数名，默认：limit
            }
            , cols: [
                [
                    {type: 'checkbox', fixed: 'left'},
                    {
                        field: 'id',
                        title: '用户id',
                        align: 'center'
                    },
                    {
                        field: 'userName',
                        title: '用户名',
                        align: 'center'
                    },
                    {
                        title: '操作',
                        fixed: 'right',
                        align: 'center',
                        toolbar: '#hidden1-table-tool'
                    }
                ]
            ]
        };

        //点击弹出的弹层上的表格中“选中”按钮的触发函数
        function tool_event_handler(obj) {
            console.info(obj);
            var data = obj.data;
            switch (obj.event) {
                case 'select':
                    layui.$('#projectManager').val(data.userName);
                    layui.$('#manager').val(data.id);
                    layui.layer.close(layer.index);
                    break;
            }
        }

        // 输入框的光标聚焦事件的触发函数， 弹出弹层，弹层上显示所有的客户，以供选择。
        function input_focus_handler() {
            layer.open({
                type: 1
                , area: ['600px', '450px']
                , content: $('#hidden1')
                , success: function () {
                    // 重新加载表格中的数据
                    layui.table.reload('user_result', user_result_table_options);
                    layui.$('#hidden1').css('display', 'block');
                }
            });
        }

        // part 2: 让layui渲染页面
        layui.table.render(user_result_table_options); // 渲染页面上的table. table中 的数据是通过 ajax 请求从后台获取。

        // part 3: 让 layui 为页面的元素绑定事件处理函数
        layui.table.on('tool(projectManager_result)', tool_event_handler); // 为页面上的table上的tool绑定事件处理函数

        // part 4: 为输入框绑定光标聚焦事件的触发该函数，
        layui.$('#projectManager').focus(input_focus_handler);


        //创建一个编辑器
        var editIndex = layedit.build('LAY_demo_editor');

        //自定义验证规则
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符';
                }
            }
            , pass: [/(.+){6,12}$/, '密码必须6到12位']
            , content: function (value) {
                layedit.sync(editIndex);
            }
        });

        //监听指定开关
        form.on('switch(switchStatus)', function (data) {
            this.value = this.checked ? "0" : "1";
        });

        var $ = layui.$;
        //监听提交
        form.on('submit(formDemo)', function (data) {
            data.field.status = data.field.status ? "0" : "1";
            var deptId = selectCheckeds();
            var flag = true;
            if (deptId == '' || deptId == null || deptId == undefined) {
                parent.layer.msg('请选择部门！');
                flag = false;
            } else {
                data.field.deptId = deptId;
                $.ajax({
                    type: 'POST',
                    url: "/project/add",
                    data: data.field,
                    async: false,
                    success: function (res) {
                        if (res.code == 0) {
                            layer.msg('新增成功！', {
                                time: 3000    //2秒关闭（如果不配置，默认是3秒）
                            }, function () {
                                layer.closeAll();
                                window.location.reload();
                            });
                        } else {
                            layer.msg("增加失败" + res.msg);
                            flag = false;
                        }
                    }
                });
            }
            return flag;
        });
    });
</script>

<script>
    // 树结构初始化加载
    var setting = {
        check: {enable: true, nocheckInherit: true, chkboxType: {"Y": "ps", "N": "ps"}},
        view: {selectedMulti: false}, data: {key: {title: "title"}, simpleData: {enable: true}},
        callback: {
            onClick: function (event, treeId, treeNode) {
                var treeId = treeNode.id;
                var treeName = treeNode.name;
                $("#treeId").val(treeId);
                $("#treeName").val(treeName);
            }
        }
    }, tree, loadTree = function () {
        $.get("/system/dept/treeData", function (data) {
            var treeName = $("#treeName").val();
            tree = $.fn.zTree.init($("#tree"), setting, data);
            // 展开第一级节点
            var nodes = tree.getNodesByParam("level", 0);
            for (var i = 0; i < nodes.length; i++) {
                tree.expandNode(nodes[i], true, false, false);
                selectCheckNode(treeName, nodes[i]);
            }
            // 展开第二级节点
            nodes = tree.getNodesByParam("level", 1);
            for (var i = 0; i < nodes.length; i++) {
                tree.expandNode(nodes[i], true, false, false);
                selectCheckNode(treeName, nodes[i]);
            }
            // 展开第二级节点
            nodes = tree.getNodesByParam("level", 2);
            for (var i = 0; i < nodes.length; i++) {
                tree.expandNode(nodes[i], true, false, false);
                selectCheckNode(treeName, nodes[i]);
            }
        }, null, null, "正在加载，请稍后...");
    };

    $(function () {
        loadTree();
    });

    function selectCheckeds() {
        var menuIds = "";
        var treeNodes = tree.getCheckedNodes(true);
        for (var i = 0; i < treeNodes.length; i++) {
            if (treeNodes[i].getCheckStatus().half != true) {
                if (menuIds == "") {
                    menuIds = treeNodes[i].id;
                } else {
                    menuIds += ("," + treeNodes[i].id);
                }
            }
        }
        return menuIds;
    }

    function selectCheckNode(treeName, node) {
        if (treeName == node.name) {
            tree.selectNode(node, true);
        }
    }

</script>
</body>
</html>